const http = require('http')
const app = require('./module/routes')
const ejs = require('ejs')

const { MongoClient } = require('mongodb')
const url = 'mongodb://admin:123456@localhost:27017'; // 权限
const dbName = 'itying'
const client = new MongoClient(url)

http.createServer(app).listen(8081)

app.static('public') // 修改默认静态web目录

// 配置路由
app.get('/', function(req, res) {
  // res.writeHead(200, {'Content-Type': 'text/html;charset=urf-8'})
  // res.end('home')
  let msg = '数据库里面获取的数据';
  client.connect((err) => {
    if(err) {
      console.log(err);
      return;
    }
    const db = client.db(dbName); 
    db.collection('user').find({}).toArray((err, result) => {
      if(err) {
        console.log(err);
        return;
      }
      client.close()
      ejs.renderFile("./views/list.ejs", {
        list: result,
        msg: msg
      }, (err, data) => {
        res.send(data)
      })
    })
  })
})

app.get('/news', function(req, res) {
  res.send('news')
})

app.get('/login', function(req, res) {
  ejs.renderFile('./views/form.ejs', {}, (err, data) => {
    res.send(data)
  })
})

app.post('/login', function(req, res) {
  res.send(req.body)
})
